<template>
    <div>
        <v-container>
            <v-row>
                <v-col>
                    <v-card outline tile>
                        <v-card-title>用户列表</v-card-title>
                        <v-data-table :headers="headers" :items="usersInfo">
                            <template v-slot:[`item.type`]="{ item }">
                                <div v-text="userTypes.find(itemToFind => itemToFind.id == item.type).name"></div>
                            </template>
                            <template v-slot:[`item.seqNum`]="{ item }">
                                <v-icon v-if="item.seqNum !== null">mdi-check</v-icon>
                                <v-icon v-else>mdi-close</v-icon>
                            </template>
                            <template v-slot:[`item.label`]="{ item }">
                                <v-icon v-if="item.label !== null">mdi-check</v-icon>
                                <v-icon v-else>mdi-close</v-icon>
                            </template>
                            <template v-slot:[`item.password`]="{ item }">
                                <v-icon v-if="item.password !== null">mdi-check</v-icon>
                                <v-icon v-else>mdi-close</v-icon>
                            </template>
                            <template v-slot:[`item.actions`]="{ item }">
                                <v-icon small class="mr-2" @click="editItem(item)">
                                    mdi-pencil
                                </v-icon>
                                <v-icon small @click="deleteItem(item)">
                                    mdi-delete
                                </v-icon>
                            </template>
                            <template v-slot:no-data>
                                没有数据！
                            </template>
                        </v-data-table>
                    </v-card>
                </v-col>
            </v-row>
            <v-row>
                <v-col>
                    <v-card flat>
                        <v-card-title>用户添加</v-card-title>
                        <v-form ref="form" v-model="valid" lazy-validation>
                            <v-text-field v-model="name" :counter="10" :rules="nameRules" label="用户名"
                                required></v-text-field>
                            <v-select v-model="type"
                                :items="userTypes.map(item => ({ text: item.name, value: item.id }))"
                                :rules="[v => !!v || '必须选择一个用户类型']" label="用户类型" required></v-select>
                            <v-btn :disabled="!valid || pendingAddByICCard" :loading="pendingAddByICCard" class="mr-4"
                                color="primary" @click="addUserByICCard">
                                IC卡添加
                                <template v-slot:loader>
                                    <span>请放卡...</span>
                                </template>
                            </v-btn>
                            <v-btn :disabled="!valid || pendingAddByFace" :loading="pendingAddByFace" class="mr-4"
                                color="primary" @click="addUserByFace">
                                人脸添加
                            </v-btn>
                            <v-btn :disabled="!valid" color="primary"
                                @click="modifyingPassword = false; dialogInputPassword = true">
                                密码添加
                            </v-btn>
                        </v-form>
                    </v-card>
                </v-col>
            </v-row>
            <v-row>
                <v-col>
                    <v-card flat>
                        <v-card-title>用户登录</v-card-title>
                        <v-form>
                            <v-btn :disabled="pendingLoginByICCard || pendingLoginByFace"
                                :loading="pendingLoginByICCard" class="mr-4" color="primary"
                                @click="loginByICCard">IC卡登录
                                <template v-slot:loader>
                                    <span>请放卡...</span>
                                </template>
                            </v-btn>
                            <v-btn :disabled="pendingLoginByFace || pendingLoginByICCard" :loading="pendingLoginByFace"
                                class="mr-4" color="primary" @click="loginByFace">人脸登录
                            </v-btn>
                            <v-btn color="primary" @click="dialogLogin = true">密码登录
                            </v-btn>
                        </v-form>
                    </v-card>
                </v-col>
            </v-row>
        </v-container>
        <v-dialog v-model="dialogEdit" max-width="700px">
            <v-card>
                <v-card-title>用户编辑</v-card-title>
                <v-card-actions>
                    <v-btn :disabled="pendingModifyICCard || pendingModifyFace" :loading="pendingModifyICCard"
                        @click="modifyUserICCard">IC卡绑定
                        <template v-slot:loader>
                            <span>请放卡...</span>
                        </template>
                    </v-btn>
                    <v-btn @click="clearUserICCard">IC卡解绑
                    </v-btn>
                    <v-spacer></v-spacer>
                    <v-btn :disabled="pendingModifyFace || pendingModifyICCard" :loading="pendingModifyFace"
                        @click="modifyUserFace">人脸录入
                    </v-btn>
                    <v-btn @click="clearUserFace">人脸删除
                    </v-btn>
                    <v-spacer></v-spacer>
                    <v-btn @click="modifyingPassword = true; dialogInputPassword = true">密码修改
                    </v-btn>
                    <v-btn @click="clearUserPassword">密码清除</v-btn>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" text @click="dialogEdit = false">
                        关闭
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="dialogDelete" max-width="300px">
            <v-card>
                <v-card-title class="text-h6">确定要删除这个用户吗？</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" text @click="dialogDelete = false">取消</v-btn>
                    <v-btn color="blue darken-1" text @click="deleteUser">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="dialogInputPassword" max-width="300px">
            <v-card class="pa-6">
                <v-form ref="inputPasswordForm" v-model="validPassword" lazy-validation>
                    <v-text-field v-model="password" :counter="20" :rules="passwordRules" :type="'password'" label="密码"
                        required>
                    </v-text-field>
                    <v-text-field v-model="passwordAgain" :counter="20" :rules="passwordRules" :type="'password'" label="再次输入密码" 
                        required>
                    </v-text-field>
                    <v-btn v-if="modifyingPassword == false" :disabled="!validPassword" class="mr-4"
                        @click="addUserByPassword">
                        确定
                    </v-btn>
                    <v-btn v-else :disabled="!validPassword" class="mr-4" @click="modifyUserPassword">
                        确定
                    </v-btn>
                    <v-btn @click="dismissInputPasswordDlg">
                        取消
                    </v-btn>
                </v-form>
            </v-card>
        </v-dialog>
        <v-dialog v-model="dialogLogin" max-width="300px">
            <v-card class="pa-6">
                <v-form ref="loginByPasswordForm" v-model="validPasswordLogin" lazy-validation>
                    <v-text-field v-model="username" :counter="10" :rules="nameRules" label="用户名" required>
                    </v-text-field>
                    <v-text-field v-model="password" :counter="20" :rules="passwordRules" :type="'password'" label="密码"
                        required>
                    </v-text-field>
                    <v-btn :disabled="!validPasswordLogin" class="mr-4" @click="loginByPassword">
                        确定
                    </v-btn>
                    <v-btn @click="dismissLoginByPasswordDlg">
                        取消
                    </v-btn>
                </v-form>
            </v-card>
        </v-dialog>
        <v-snackbar v-if="!failed" v-model="alert" :timeout="3000" color="success">
            {{ info }}
        </v-snackbar>
        <v-snackbar v-else v-model="alert">
            {{ info }}

            <template v-slot:action="{ attrs }">
                <v-btn color="red" text v-bind="attrs" @click="alert = false">
                    关闭
                </v-btn>
            </template>
        </v-snackbar>
    </div>
</template>

<script>
export default {
    data: () => ({
        headers: [
            {
                text: '姓名',
                value: 'name',
            },
            {
                text: '类型',
                value: 'type',
            },
            {
                text: 'IC卡信息',
                value: 'seqNum',
            },
            {
                text: '人脸信息',
                value: 'label',
            },
            {
                text: '密码信息',
                value: 'password',
            },
            {
                text: '操作',
                value: 'actions',
            }
        ],
        userTypes: [
            {
                id: 1,
                name: '操作员',
            },
            {
                id: 2,
                name: '管理员',
            }
        ],
        usersInfo: [
            {
                id: 1,
                type: 2,
                name: 'Admin',
                label: null,
                seqNum: null,
                password: null,
            },
            {
                id: 2,
                type: 1,
                name: '刘康',
                label: null,
                seqNum: null,
                password: null,
            }
        ],
        dialogEdit: false,
        dialogDelete: false,
        id: -1,

        valid: true,
        nameRules: [
            v => !!v || "用户名不能为空",
            v => (v && v.length <= 10) || "用户名必须小于10个字符",
        ],
        name: '',
        type: null,
        passwordRules: [
            v => !!v || '密码不能为空',
            v => (v && v.length <= 20) || '密码必须小于20个字符',
        ],
        password: '',
        passwordAgain: '',

        pendingAddByICCard: false,
        pendingAddByFace: false,

        pendingModifyICCard: false,
        pendingModifyFace: false,

        pendingLoginByICCard: false,
        pendingLoginByFace: false,

        modifyingPassword: false,

        alert: false,
        failed: false,
        info: '',

        dialogInputPassword: false,
        validPassword: false,

        dialogLogin: false,
        validPasswordLogin: false,
        username: '',
    }),
    methods: {
        editItem(item) {
            this.id = item.id
            this.dialogEdit = true
        },
        deleteItem(item) {
            this.id = item.id
            this.dialogDelete = true
        },
        addUserByICCard() {
            if (this.$refs.form.validate()) {
                this.pendingAddByICCard = true
                this.userManage.addUserByICCard(this.name, this.type)
            }
        },
        addUserByFace() {
            if (this.$refs.form.validate()) {
                this.pendingAddByFace = true
                this.userManage.addUserByFace(this.name, this.type)
            }
        },
        addUserByPassword() {
            if (this.$refs.inputPasswordForm.validate()) {
                if (this.password !== this.passwordAgain) {
                    this.info = "密码不一致，请重新输入..."
                    this.failed = true
                    this.alert = true
                    return
                }

                this.userManage.addUserByPassword(this.name, this.type, this.password)
            }
        },
        modifyUserICCard() {
            this.pendingModifyICCard = true
            this.userManage.modifyUserICCard(this.id)
        },
        modifyUserFace() {
            this.pendingModifyFace = true
            this.userManage.modifyUserFace(this.id)
        },
        modifyUserPassword() {
            if (this.$refs.inputPasswordForm.validate()) {
                if (this.password !== this.passwordAgain) {
                    this.info = "密码不一致，请重新输入..."
                    this.failed = true
                    this.alert = true
                    return
                }

                this.userManage.modifyUserPassword(this.id, this.password)
            }
        },
        clearUserICCard() {
            this.userManage.clearUserICCard(this.id).then(retVal => retVal === true ? onClearSuccess() : onClearFail())
        },
        clearUserFace() {
            this.userManage.clearUserFace(this.id).then(retVal => retVal === true ? onClearSuccess() : onClearFail())
        },
        clearUserPassword() {
            this.userManage.clearUserPassword(this.id).then(retVal => retVal === true ? onClearSuccess() : onClearFail())
        },
        deleteUser() {
            this.userManage.deleteUser(this.id).then(retVal => {
                if (retVal === true) {
                    this.info = "删除成功。"
                    this.failed = false
                    this.alert = true

                    this.dialogDelete = false

                    this.userManage.getUserList().then(retVal => this.usersInfo = JSON.parse(retVal))
                }
                else {
                    this.info = "删除失败，原因：" + errInfo
                    this.failed = true
                    this.alert = true
                }
            })
        },
        loginByICCard() {
            this.userManage.loginByICCard()
            this.pendingLoginByICCard = true
        },
        loginByFace() {
            this.userManage.loginByFace()
            this.pendingLoginByFace = true
        },
        loginByPassword() {
            this.userManage.loginByPassword(this.username, this.password)
        },
        onClearSuccess() {
            this.info = "清除成功"
            this.failed = false
            this.alert = true

            this.userManage.getUserList().then(retVal => this.usersInfo = JSON.parse(retVal))
        },
        onClearFail() {
            this.info = "清除失败"
            this.failed = true
            this.alert = true
        },
        dismissInputPasswordDlg() {
            if (this.dialogInputPassword == true) {
              this.$refs.inputPasswordForm.reset()
              this.dialogInputPassword = false
            }
        },
        dismissLoginByPasswordDlg() {
            if (this.dialogLogin == true) {
              this.$refs.loginByPasswordForm.reset()
              this.dialogLogin = false
            }
        },
        onUserAdded(succeed, errInfo) {
            if (succeed) {
                this.dismissInputPasswordDlg()

                this.pendingAddByICCard = false
                this.pendingAddByFace = false

                this.info = "添加成功"
                this.failed = false
                this.alert = true

                this.$refs.form.reset()
                this.$refs.form.resetValidation()

                this.userManage.getUserList().then(retVal => this.usersInfo = JSON.parse(retVal))
            } else {
                this.pendingAddByICCard = false
                this.pendingAddByFace = false

                this.info = "添加失败，原因：" + errInfo
                this.failed = true
                this.alert = true
            }
        },
        onUserModified(succeed, errInfo) {
            if (succeed) {
                this.dismissInputPasswordDlg()

                this.pendingModifyICCard = false
                this.pendingModifyFace = false

                this.info = "修改成功"
                this.failed = false
                this.alert = true

                this.userManage.getUserList().then(retVal => this.usersInfo = JSON.parse(retVal))
            } else {
                this.pendingModifyICCard = false
                this.pendingModifyFace = false

                this.info = "修改失败，原因：" + errInfo
                this.failed = true
                this.alert = true
            }
        },
        onUserLogined(succeed, resultOrErrInfo) {
            if (succeed) {
                this.dismissLoginByPasswordDlg()

                this.pendingLoginByFace = false
                this.pendingLoginByICCard = false

                let id = parseInt(resultOrErrInfo)

                let userInfo = this.usersInfo.find(item => item.id == id)
                let userType = this.userTypes.find(item => item.id == userInfo.type)

                this.info = "登录成功，用户名：" + userInfo.name + "，类型：" + userType.name + "。"
                this.failed = false
                this.alert = true
            } else {
                this.pendingLoginByFace = false
                this.pendingLoginByICCard = false

                this.info = "登录失败，原因：" + resultOrErrInfo
                this.failed = true
                this.alert = true
            }
        },
    },

    mounted: async function () {
        this.userManage.userAdded.connect(this.onUserAdded)
        this.userManage.userModified.connect(this.onUserModified)
        this.userManage.userLogined.connect(this.onUserLogined)

        this.userTypes = JSON.parse(await this.userManage.getUserTypes())
        this.userManage.getUserList().then(retVal => this.usersInfo = JSON.parse(retVal))
    },

    unmounted: function () {
        this.userManage.userAdded.disconnect(this.onUserAdded)
        this.userManage.userModified.disconnect(this.onUserModified)
        this.userManage.userLogined.disconnect(this.onUserLogined)
    },
}
</script>